@file:OptIn(ExperimentalMaterialApi::class)

package com.example.mycomposelesson.ui

import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices.NEXUS_5X
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

import coil.compose.AsyncImage

import com.example.mycomposelesson.R
import com.example.mycomposelesson.ui.theme.MyComposeLessonTheme
import com.example.mycomposelesson.util.LogUtil.logger


@Preview(name="控件测试",
    showBackground = true,
    widthDp = 1920,
    heightDp = 1024,
   // device = NEXUS_5X
)
@Composable
fun preControlTest(){
    MyComposeLessonTheme {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colors.background
        ){
            ControlTest()
        }
    }
}
fun myImageButtonClick()
{
    logger.debug { "我让点了!" }
}
@Composable
fun ControlTest(){
    var openDialog = remember { mutableStateOf(false) }
    Column(modifier=Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.SpaceBetween) {
        Button(onClick = { openDialog.value=true },
              modifier= Modifier
                  .fillMaxWidth()
                  .padding(start = 10.dp, end = 10.dp, top = 10.dp)) {
            Text(text="对话框测试", style = MaterialTheme.typography.h5)
        }
        TestButton()
        ImageDemo()
        SliderDemo()
        TextDemo()
        BadgeDemo()
        TextFieldDemo()
       // BottomNavigationDemo()
    }

    //提示对话框
    TestDialog(openDialog)
}

@Composable
fun TestDialog(openDialog:MutableState<Boolean>){
    if (openDialog.value) {
        AlertDialog(
            onDismissRequest = {
                // 当用户点击对话框以外的地方或者按下系统返回键将会执行的代码
                openDialog.value = false
            },
            title = {
                Text(
                    text = "开启位置服务",
                    fontWeight = FontWeight.W700,
                    style = MaterialTheme.typography.h6
                )
            },
            text = {
                Text(
                    text = "这将意味着，我们会给您提供精准的位置服务，并且您将接受关于您订阅的位置信息",
                    fontSize = 16.sp
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        openDialog.value = false
                        logger.error { "对话框确认了" }
                    },
                ) {
                    Text(
                        "确认",
                        fontWeight = FontWeight.W700,
                        style = MaterialTheme.typography.button
                    )
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        openDialog.value = false
                        logger.error { "对话框取消了" }
                    }
                ) {
                    Text(
                        "取消",
                        fontWeight = FontWeight.W700,
                        style = MaterialTheme.typography.button
                    )
                }
            }
        )
    }
}
@Composable
fun TestButton(){
    Row(modifier= Modifier
        .fillMaxWidth()
        .padding(10.dp), horizontalArrangement = Arrangement.SpaceEvenly) {
        //普通的Button
        Button(onClick = { logger.error { "TestButton is click!" } }) {
            Icon(
                // Material 库中的图标，有 Filled, Outlined, Rounded, Sharp, Two Tone 等
                Icons.Filled.Favorite,
                contentDescription = null,
                modifier = Modifier.size(ButtonDefaults.IconSize)
            )
            Spacer(Modifier.size(ButtonDefaults.IconSpacing))
            Text("喜欢",style= MaterialTheme.typography.h6)
        }
        //一个 FloatActionButton（FAB）代表一个屏幕的主要行为
        ExtendedFloatingActionButton(
            icon = { Icon(Icons.Filled.Done, contentDescription = null) },
            text = { Text("添加到我喜欢的") },
            onClick = { logger.error { "ExtendedFloatingActionButton is clicked!" } }
        )
        IconButton(onClick = { /*TODO*/ }) {
            Icon(Icons.Filled.Search, null)
        }
        IconButton(onClick = { /*TODO*/ }) {
            Icon(Icons.Filled.ArrowBack, null)
        }
        IconButton(onClick = { /*TODO*/ }) {
            Icon(Icons.Filled.Done, null)
        }
        MyIconButton(onClick = { myImageButtonClick()}){
            Icon(Icons.Filled.Favorite,null)
        }
    }

}

@Composable
fun MyIconButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    content: @Composable () -> Unit
) {
    // 这也是源码的一部分
    val IconButtonSizeModifier = Modifier.size(48.dp)
    Box(
        modifier = modifier
            .clickable(
                onClick = onClick,
                enabled = enabled,
                role = Role.Button,
                interactionSource = interactionSource,
                indication = null
            )
            .then(IconButtonSizeModifier),
        contentAlignment = Alignment.Center
    ) { content() }
}

/***
 * Image Test
 */
@Composable
fun ImageDemo() {
    Row(modifier= Modifier
        .fillMaxWidth()
        .padding(start = 10.dp),
    horizontalArrangement = Arrangement.SpaceEvenly){
        Surface(
            shape = CircleShape,
            border = BorderStroke(5.dp, Color.Gray)
        ) {
            Image(
                painter = painterResource(id = R.drawable.img),
                contentDescription = "德尔塔与豆豆",
                modifier = Modifier
                    .size(150.dp)
                    .clickable {
                        logger.error { "delta is Clicked!" }
                    },
                contentScale = ContentScale.Crop
            )
        }
        AsyncImage(
            model = "https://picsum.photos/300/300",
            contentDescription = null,
            modifier = Modifier.size(150.dp),
            contentScale= ContentScale.Fit
        )
    }


}

/***
 * Slider Test
 */
@Composable
fun SliderDemo(){
   Row(modifier=Modifier.fillMaxWidth(),
   horizontalArrangement = Arrangement.SpaceBetween){
       var sliderPosition by remember { mutableStateOf(0f) }
       Text(text = sliderPosition.toInt().toString(),
           textAlign=TextAlign.Center,
           style=MaterialTheme.typography.h5,
           modifier = Modifier
               .padding(top = 5.dp))
       Slider(
           value = sliderPosition,
           onValueChange = { sliderPosition = it },
           modifier=Modifier.height(10.dp),
           valueRange = 0f..32f,
           onValueChangeFinished = {
               // launch some business logic update with the state you hold
               // viewModel.updateSelectedSliderValue(sliderPosition)
           },
           steps = 32,
           colors = SliderDefaults.colors(
               thumbColor = MaterialTheme.colors.secondary,
               activeTrackColor = MaterialTheme.colors.secondaryVariant
           )
       )
   }
}

@Composable
fun BadgeDemo(){
    Row(modifier=Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceEvenly){
        BadgedBox(badge = { Badge { Text("8") } }) {
            Icon(
                Icons.Filled.Favorite,
                contentDescription = "Favorite"
            )
        }
    }
}
@Composable
fun TextDemo(){
   Row(modifier=Modifier.fillMaxWidth(),
   horizontalArrangement = Arrangement.Start,
   verticalAlignment = Alignment.Bottom){

       Text(
           text = "你好呀",
           style = MaterialTheme.typography.h1
       )
       Text(
           text = "你好呀",
           style = MaterialTheme.typography.h2
       )
       Text(
           text = "你好呀",
           style = MaterialTheme.typography.h3
       )
       Text(
           text = "你好呀",
           style = MaterialTheme.typography.h4
       )
       Text(
           text = "你好呀",
           style = MaterialTheme.typography.h5
       )
       Text(
           text = "你好呀",
           style = MaterialTheme.typography.h6
       )
       Text(
           text ="你好呀",
           style = MaterialTheme.typography.subtitle1
       )
       Text(
           text ="你好呀",
           style = MaterialTheme.typography.subtitle2
       )
       Text(
           text ="你好呀",
           style = MaterialTheme.typography.body1
       )
       Text(
           text ="你好呀",
           style = MaterialTheme.typography.body2
       )
       Text(
               text ="你好呀",
       style = MaterialTheme.typography.button
       )
       Text(
           text ="你好呀",
           style = MaterialTheme.typography.caption
       )
       Text(
           text ="你好呀",
           style = MaterialTheme.typography.overline
       )

   }
}
@Composable
fun TextFieldDemo(){
    var text by remember{ mutableStateOf("")}
    var passwordHidden by remember{ mutableStateOf(true)}

    TextField(
        value = text,
        textStyle = MaterialTheme.typography.h4,
        onValueChange = {
            text = it
        },
        keyboardOptions= KeyboardOptions(
            keyboardType = KeyboardType.NumberPassword
        ),
        modifier = Modifier.padding(start=20.dp).fillMaxWidth(),
        label = {
            Text("密码")
        },

        trailingIcon = {
            IconButton(onClick = {
                passwordHidden=!passwordHidden
            }){
                Icon(Icons.Filled.Send, null)
            }
        },
        visualTransformation = if(passwordHidden) PasswordVisualTransformation() else VisualTransformation.None
    )
}
@Composable
fun BottomNavigationDemo(){
    var selectedItem by remember { mutableStateOf(0) }
    val items = listOf("Songs", "Artists", "Playlists")
    BottomNavigation {
        items.forEachIndexed { index, item ->
            BottomNavigationItem(
                icon = {
                    when(index){
                        0->Icon(Icons.Filled.AccessAlarm,contentDescription = null)
                        1->Icon(Icons.Filled.Backpack,contentDescription = null)
                        2->Icon(Icons.Filled.Favorite,contentDescription = null)
                    }
                },
                label = { Text(item) },
                selected = selectedItem == index,
                onClick = { selectedItem = index }
            )
        }
    }
}